﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyEmulators2
{
    public delegate string ProgressDialogDelegate(object item);

    public partial class Conf_ProgressDialog : Form
    {
        object[] items = null;
        ProgressDialogDelegate progressDelegate = null;
        System.Threading.Thread worker = null;

        volatile bool doWork = false;

        public Conf_ProgressDialog(object[] items, ProgressDialogDelegate progressDelegate)
        {
            InitializeComponent();
            this.items = items;
            this.progressDelegate = progressDelegate;

            statusLabel.Text = "";
        }

        private void Conf_ProgressDialog_Load(object sender, EventArgs e)
        {
            int total = items.Length;
            if (total == 0)
                Close();

            doWork = true;

            worker = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
                {
                    for (int x = 1; x <= items.Length; x++)
                    {
                        if (!doWork)
                            return;

                        string status = string.Format("{0} / {1} - {2}", x, total, progressDelegate(items[x - 1]));
                        int perc = (int)Math.Round(((double)x / total) * 100);
                        updateStatusInfo(status, perc);
                    }

                }

                ));

            worker.Start();
        }

        void updateStatusInfo(string status, int perc)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new MethodInvoker(delegate() 
                    { 
                        updateStatusInfo(status, perc); 
                    }
                    ));
                return;
            }

            if (perc < 0)
                perc = 0;
            else if (perc > 100)
                perc = 100;
            
            statusLabel.Text = status;
            progressBar.Value = perc;
            
            if (perc == 100)
                Close();
        }

        void Conf_ProgressDialog_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (worker != null && worker.IsAlive)
            {
                doWork = false;
                worker.Join();
            }
        }
    }
}
